package com.ywb.aop;


import com.ywb.mapper.OperateLogMapper;
import com.ywb.pojo.OperateLog;
import com.ywb.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;


@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.ywb.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        OperateLog operateLog = new OperateLog();
        long costTime = end - start;
        operateLog.setCostTime(costTime);
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setReturnValue(result !=null ? result.toString() : "无返回值");
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setOperateEmpId(getCurrentUseId());
        log.info("操作日志：{}",operateLog);

        operateLogMapper.insert(operateLog);
        return result;

    }

    private Integer getCurrentUseId() {

        return CurrentHolder.getCurrentId();
    }

}
